// 获取url的参数
function getUrlParamValue(name) {
    if (name == null || name === 'undefined') {return null; }
    let searchStr = decodeURI(location.search);
    let infoIndex = searchStr.indexOf(name + "=");
    if (infoIndex === -1) { return null; }
    let searchInfo = searchStr.substring(infoIndex + name.length + 1);
    let tagIndex = searchInfo.indexOf("&");
    if(tagIndex !== -1) { searchInfo = searchInfo.substring(0, tagIndex); }
    return searchInfo;
};

// 创建XMLHttpRequest对象的通用函数
function createXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

// 通用的AJAX请求函数
function makeRequest(url, onSuccess, onError) {
    const req = createXMLHttpRequest();
    
    req.onreadystatechange = function() {
        if (req.readyState === 4) {
            if (req.status === 200) {
                onSuccess(req.responseText);
            } else {
                onError("请求失败，状态码: " + req.status);
            }
        }
    };
    
    req.onerror = function() {
        onError("网络请求失败");
    };
    
    req.ontimeout = function() {
        onError("请求超时");
    };
    
    req.open("GET", url, true);
    req.send();
}

// 解析API响应的通用函数
function parseApiResponse(responseText) {
    try {
        const response = JSON.parse(responseText);
        
        // 检查响应格式，支持新的JSON格式和旧的数组格式
        if (response.code !== undefined && response.data !== undefined) {
            // 新的JSON响应格式
            return {
                success: response.code === 200,
                data: response.data,
                message: response.message
            };
        } else {
            // 旧的数组格式（向后兼容）
            return {
                success: true,
                data: response,
                message: null
            };
        }
    } catch (e) {
        return {
            success: false,
            data: null,
            message: "解析响应数据失败: " + e.message
        };
    }
}

// 显示错误信息的通用函数
function showError(elementId, message) {
    document.getElementById(elementId).innerHTML = "<div class='alert alert-danger'>" + message + "</div>";
}

// 显示信息的通用函数
function showInfo(elementId, message) {
    document.getElementById(elementId).innerHTML = "<div class='alert alert-info'>" + message + "</div>";
}

// 显示警告信息的通用函数
function showWarning(elementId, message) {
    document.getElementById(elementId).innerHTML = "<div class='alert alert-warning'>" + message + "</div>";
}

// 渲染实例表格的函数
function renderInstanceTable(instanceList) {
    let html = "<div class=\"table-responsive\"><table class=\"table table-hover\">\n" +
        "  <thead>\n" +
        "    <tr>\n" +
        "      <th><i class=\"bi bi-tag\"></i> 服务名</th>\n" +
        "      <th><i class=\"bi bi-globe\"></i> 实例IP</th>\n" +
        "      <th><i class=\"bi bi-plug\"></i> 端口</th>\n" +
        "      <th><i class=\"bi bi-speedometer2\"></i> 权重</th>\n" +
        "      <th><i class=\"bi bi-heart-pulse\"></i> 健康状态</th>\n" +
        "      <th><i class=\"bi bi-gear\"></i> 操作</th>\n" +
        "    </tr>\n" +
        "  </thead>\n" +
        "  <tbody>";
        
    for(let i = 0; i < instanceList.length; i++) {
        const instance = instanceList[i];
        const healthStatus = instance.isHealth ? 
            "<span class=\"badge status-healthy\"><i class=\"bi bi-check-circle\"></i> 健康</span>" : 
            "<span class=\"badge status-unhealthy\"><i class=\"bi bi-x-circle\"></i> 不健康</span>";
        
        html += "    <tr>\n" +
            "      <td><strong>" + instance.serviceName + "</strong></td>\n" +
            "      <td><code>" + instance.ip + "</code></td>\n" +
            "      <td><span class=\"badge bg-secondary\">" + instance.port + "</span></td>\n" +
            "      <td><span class=\"badge bg-info\">" + instance.weight + "</span></td>\n" +
            "      <td>" + healthStatus + "</td>\n" +
            "      <td>" +
            "        <button type=\"button\" class=\"btn btn-sm btn-outline-danger\" onclick='offline(\"" + instance.serviceName + "\",\"" + instance.ip + "\",\"" + instance.port + "\")''>" +
            "          <i class=\"bi bi-stop-circle\"></i> 下线" +
            "        </button>" +
            "        <button type=\"button\" class=\"btn btn-sm btn-outline-success\" onclick='online(\"" + instance.serviceName + "\",\"" + instance.ip + "\",\"" + instance.port + "\")''>" +
            "          <i class=\"bi bi-play-circle\"></i> 上线" +
            "        </button>" +
            "      </td>\n" +
            "    </tr>";
    }
    
    html += "  </tbody>\n</table></div>";
    document.getElementById("instance").innerHTML = html;
}

// 处理实例操作响应的通用函数
function handleInstanceOperationResponse(responseText) {
    try {
        const response = JSON.parse(responseText);
        if (response.code !== undefined) {
            // 新的JSON响应格式
            if (response.code === 200) {
                alert(response.message || "操作成功");
                search(); // 刷新实例列表
            } else {
                alert("操作失败: " + response.message);
            }
        } else {
            // 旧的文本格式（向后兼容）
            if (responseText !== "") {
                alert(responseText);
                search(); // 刷新实例列表
            }
        }
    } catch (e) {
        // 如果不是JSON格式，按文本处理
        if (responseText !== "") {
            alert(responseText);
            search(); // 刷新实例列表
        }
    }
}

// 根据服务名获取实例列表
function getInstanceListByServiceName(serviceName) {
    makeRequest(
        "/api/instance/list?serviceName=" + serviceName,
        function(responseText) {
            const result = parseApiResponse(responseText);
            
            if (!result.success) {
                showError("instance", result.message);
                return;
            }
            
            const instanceList = result.data || [];
            
            if (!Array.isArray(instanceList)) {
                showWarning("instance", "实例数据格式错误");
                return;
            }
            
            if (instanceList.length === 0) {
                showInfo("instance", "暂无实例数据");
                return;
            }
            
            renderInstanceTable(instanceList);
        },
        function(errorMessage) {
            showError("instance", errorMessage);
        }
    );
}

function search(){
    let serviceName = getUrlParamValue("serviceName");
    document.getElementById("name").innerHTML = "<i class=\"bi bi-server\"></i> 当前服务：<strong>"+serviceName+"</strong>"
    getInstanceListByServiceName(serviceName);
}

// 手动下线
function offline(serviceName, ip, port){
    makeRequest(
        "/api/instance/offline?serviceName=" + serviceName + "&ip=" + ip + "&port=" + port,
        handleInstanceOperationResponse,
        function(errorMessage) {
            alert(errorMessage);
        }
    );
}

// 手动上线
function online(serviceName, ip, port){
    makeRequest(
        "/api/instance/online?serviceName=" + serviceName + "&ip=" + ip + "&port=" + port,
        handleInstanceOperationResponse,
        function(errorMessage) {
            alert(errorMessage);
        }
    );
}

// 页面加载成功之后
window.onload = function (){
    search();
};

setInterval(search, 5000);
